package io.renren.socket;


import io.renren.modules.substation.entity.*;
import io.renren.modules.substation.service.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class InitPointInfoDataConfService {

    public static Logger logger = LoggerFactory.getLogger(InitPointInfoDataConfService.class);

    //InitPointInfoDataConfService.cache.put("Point",list);
    public static final Map<String,List<TPointInfoDataConfEntity>> cache = new HashMap<String,List<TPointInfoDataConfEntity>>();
    public static final Map<String,AlarmSendingOutInfo> cache2 = new HashMap<String,AlarmSendingOutInfo>();


    @Autowired
    private TPointInfoDataConfService tPointInfoDataConfService;
//    @Autowired
//    private RedisUtil redisUtil;

    public void initPointInfo() {

//        Properties prop = new Properties();
//        try {
//            File file = new File(filePath);
//            if (!file.exists())
//                file.createNewFile();
//            InputStream fis = new FileInputStream(file);
//            prop.load(fis);
//            //一定要在修改值之前关闭fis
//            fis.close();
//            OutputStream fos = new FileOutputStream(filePath);
//            prop.setProperty(key, value);
//            //保存，并加入注释
//            prop.store(fos, "Update '" + key + "' value");
//            fos.close();
//        } catch (IOException e) {
//            System.err.println("Visit " + filePath + " for updating " + value + " value error");
//        }

//        try {
//         List<TPointInfoDataConfEntity> list = tPointInfoDataConfService.initAllSimple();
//            for (InitBean init : initBeans) {
//                String paTable = init.getPaTable();
//                String key = init.getPaId();
//                String value = init.getPaValue();
//                redisUtil.hashSet(paTable, key, value, 1441L);
//            }
//            log.info("-----【参数表参数】-----初始化成功！");
//        } catch (Exception e) {
//            log.error("初始化参数出错{}", e);
//        }
            logger.info("启动服务");
//        List<TPointInfoDataConfEntity> list = tPointInfoDataConfService.initAllSimple();
//        InitPointInfoDataConfService.cache.put("Point",list);
        new TimerOfInit().initTimer();
    }
}

@Component
class TimerOfInit {

    public static Logger logger = LoggerFactory.getLogger(TimerOfInit.class);

    @Autowired
    protected TPointInfoDataConfService tPointInfoDataConfService;
    @Autowired
    protected TBusiDevMonitorHisService tBusiDevMonitorHisService;
    @Autowired
    protected TBusiDevMonitorInfoService tBusiDevMonitorInfoService;

    @Autowired
    protected TInfoAlarmConfigService tInfoAlarmConfigService;

    @Autowired
    protected TInfoVariableInfoService tInfoVariableInfoService;

    @Autowired
    protected TBusiSysAlarmInfoService tBusiSysAlarmInfoService;
    @Autowired
    protected TBusiSysEventInfoService tBusiSysEventInfoService;

    private static TimerOfInit timerOfInit;

    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        timerOfInit = this;
        timerOfInit.tPointInfoDataConfService = this.tPointInfoDataConfService;
        timerOfInit.tBusiDevMonitorHisService = this.tBusiDevMonitorHisService;
        timerOfInit.tBusiDevMonitorInfoService = this.tBusiDevMonitorInfoService;
        timerOfInit.tInfoAlarmConfigService = this.tInfoAlarmConfigService;
        timerOfInit.tInfoVariableInfoService = this.tInfoVariableInfoService;
        timerOfInit.tBusiSysAlarmInfoService = this.tBusiSysAlarmInfoService;
    }

    public  String  getVariableCodeByName(String varName,String kind){
        String ret ="";
        TInfoVariableInfoEntity tInfoVariableInfoEntity = new TInfoVariableInfoEntity();
        tInfoVariableInfoEntity.setVariableKind(kind);
        List<TInfoVariableInfoEntity> VariableList=timerOfInit.tInfoVariableInfoService.queryVariableByCondition(tInfoVariableInfoEntity);
        for(TInfoVariableInfoEntity o : VariableList){
            if(o.getVariableName().equals(varName))
            {
                ret=String.valueOf(o.getVariableId());
            }
        }
        return ret;
    }
    /**
     * 定时执行（每分钟）
     //         */
    @Scheduled(cron = "59 * * * * ?")
    public void initTimer(){
        try {
            Date t = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
//            InitPointInfoDataConfService.cache.put("Point", timerOfInit.tPointInfoDataConfService.initAllSimple());
            List<TPointInfoDataConfEntity> list = timerOfInit.tPointInfoDataConfService.initAllSimple();
            InitPointInfoDataConfService.cache.put("Point",list);
            if(list != null) {
                InitPointInfoDataConfService.cache.put("Point", list);
                logger.debug("initTimer--");
            } else {
                logger.debug("点表为空--");
            }

//            runClientSendData.runNettyClient("1","2","ABCDEF");

            if(false) {
                TBusiDevMonitorInfoEntity tBusiDevMonitorInfoEntity = new TBusiDevMonitorInfoEntity();
                for (int i = 0; i < list.size(); i++) {
                    tBusiDevMonitorInfoEntity.setLastOpr((long) 0);
                    tBusiDevMonitorInfoEntity.setLastTime(new Date());
                    tBusiDevMonitorInfoEntity.setDevCode(list.get(i).getDevCode());
                    logger.debug("list.get(i).getDevCode():" + list.get(i).getDevCode());
                    logger.debug("list.get(i).getLastTime():" + list.get(i).getLastTime());
                    //            tBusiDevMonitorInfoEntity.setMonitorTime("" + list.get(i).getLastTime());
                    int intstr = Integer.parseInt(list.get(i).getAddPublic());
                    String str = String.format("%02x", intstr);
                    if (list.get(i).getTypeFl().equals("0")) {
                        tBusiDevMonitorInfoEntity.setVariableKind("00");
                        tBusiDevMonitorInfoEntity.setVariableValue(list.get(i).getDataValue());
                        tBusiDevMonitorInfoEntity.setVariableDesc(list.get(i).getStatusTypeDesc());
//                    df.format(t);

                        logger.debug("遥信入表");
                        if (tBusiDevMonitorInfoEntity.getVariableDesc().equals("红外双鉴")) {
                            int result = timerOfInit.tBusiSysEventInfoService.insertEventInfoBySystem(df.format(t), tBusiDevMonitorInfoEntity.getDevCode(), str + tBusiDevMonitorInfoEntity.getVariableDesc(), "红外双鉴事件");
                            if (result <= 0) {
                                logger.debug("红外双鉴insertEventInfoBySystem:" + result);
                            }
                        } else {
                            int result = timerOfInit.tBusiSysAlarmInfoService.insertAlarmInfoBySystem(df.format(t), tBusiDevMonitorInfoEntity.getDevCode(), str + tBusiDevMonitorInfoEntity.getVariableDesc(), tBusiDevMonitorInfoEntity.getVariableDesc() + "告警");
                            if (result <= 0) {
                                logger.debug("insertAlarmInfoBySystem:" + result);
                            }

                            logger.debug("准备事件");

                            result = timerOfInit.tBusiSysEventInfoService.insertEventInfoBySystem(df.format(t), tBusiDevMonitorInfoEntity.getDevCode(), str + tBusiDevMonitorInfoEntity.getVariableDesc(), tBusiDevMonitorInfoEntity.getVariableDesc() + "事件");
                            if (result <= 0) {
                                logger.debug("insertEventInfoBySystem:" + result);
                            }
                        }
                        logger.debug("遥信入表完成");

                    } else if (list.get(i).getTypeFl().equals("1")) {
                        //                if(list.get(i).getAddPublic().equals("1")) {
                        tBusiDevMonitorInfoEntity.setVariableKind(str);
                        //                }else if(list.get(i).getAddPublic().equals("2")){
                        //                    tBusiDevMonitorInfoEntity.setVariableKind("02");
                        //                }else if(list.get(i).getAddPublic().equals("3")){
                        //                    tBusiDevMonitorInfoEntity.setVariableKind("03");
                        //                }else{
                        logger.debug("list.get(i).getTypeFl():" + list.get(i).getTypeFl());
                        //                    tBusiDevMonitorInfoEntity.setVariableKind("00");
                        //                    tBusiDevMonitorInfoEntity.setVariableValue(list.get(i).getDataValue());
                        //                }
                        tBusiDevMonitorInfoEntity.setVariableValue(list.get(i).getDataValue());
                        tBusiDevMonitorInfoEntity.setVariableDesc(list.get(i).getStatusTypeDesc());
                        //                tBusiDevMonitorInfoEntity.setVariableStatus("0");
                    } else {
                        logger.debug("非遥信或遥测信号-不处理：" + list.get(i).getTypeFl());
                        continue;
                    }

                    tBusiDevMonitorInfoEntity.setVariableValue2("0");
                    tBusiDevMonitorInfoEntity.setVariableValue3("0");

                    int updsum = timerOfInit.tBusiDevMonitorInfoService.updateMonitorByCodeKindDesc(tBusiDevMonitorInfoEntity);
                    tBusiDevMonitorInfoEntity.setVariableValue2("0");
                    tBusiDevMonitorInfoEntity.setVariableValue3("0");
                    tBusiDevMonitorInfoEntity.setCreateOpr((long) 0);
                    tBusiDevMonitorInfoEntity.setCreateTime(new Date());
                    tBusiDevMonitorInfoEntity.setVariableStatus("0");
                    String codeStr = getVariableCodeByName(tBusiDevMonitorInfoEntity.getVariableDesc(), tBusiDevMonitorInfoEntity.getVariableKind());
                    if (codeStr != null && codeStr != "") {
                        tBusiDevMonitorInfoEntity.setVariableCode(codeStr);
                    } else {
                        tBusiDevMonitorInfoEntity.setVariableCode(codeStr);
                        logger.debug("code值未配置：name:" + tBusiDevMonitorInfoEntity.getVariableDesc() + " kind:" + tBusiDevMonitorInfoEntity.getVariableKind());
                        continue;
                    }

                    tBusiDevMonitorInfoEntity.setMonitorTime(df.format(t));
                    if (updsum <= 0) {
                        timerOfInit.tBusiDevMonitorInfoService.save(tBusiDevMonitorInfoEntity);
                    }

                    TBusiDevMonitorHisEntity tBusiDevMonitorHisEntity = new TBusiDevMonitorHisEntity();
                    BeanUtils.copyProperties(tBusiDevMonitorInfoEntity, tBusiDevMonitorHisEntity);
                    timerOfInit.tBusiDevMonitorHisService.save(tBusiDevMonitorHisEntity);


                    String Key = tBusiDevMonitorInfoEntity.getDevCode() + "-" + tBusiDevMonitorInfoEntity.getVariableKind() + tBusiDevMonitorInfoEntity.getVariableDesc();
                    TInfoAlarmConfigEntity tInfoAlarmConfigEntity = timerOfInit.tInfoAlarmConfigService.getCacheAlarmConfigInfo(Key);
                    if (tInfoAlarmConfigEntity != null) {
                        if (Float.valueOf(tBusiDevMonitorInfoEntity.getVariableValue()) > Float.valueOf(tInfoAlarmConfigEntity.getVariableMax())
                                || Float.valueOf(tBusiDevMonitorInfoEntity.getVariableValue()) < Float.valueOf(tInfoAlarmConfigEntity.getVariableMin())) {

                        } else {
                            logger.debug("未超过上下限阀值");
                            int updasu = timerOfInit.tInfoAlarmConfigService.updateHealthStatus(Key, "0");
                            if (updasu <= 0) {
                                logger.debug("更新告警状态返回结果:" + updasu);
                            }
                            continue;
                        }

                        logger.debug("超过上下限阀值更新告警");
                        int updasu = timerOfInit.tInfoAlarmConfigService.updateHealthStatus(Key, "1");
                        if (updasu <= 0) {
                            logger.debug("更新告警状态返回结果:" + updasu);
                        }
                    } else {
                        logger.debug("未找到对应告警数据上下限");
                    }
                }
                logger.debug("定时服务加载");
            }
        } catch (Exception e) {
            logger.error("未知错误-异常");
        }
    }
}

